import type { App } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import { notFoundAndNoPower, staticRoutes, baseRoutes } from '@/router/route'
import { local } from '@/utils/storage'
import { useAppsStore } from '@/stores/modules/app'
import { setupRouterGuard } from '@/router/guard'

export const router = createRouter({
  history: createWebHistory(),
  /**
   * 说明：
   * 1、notFoundAndNoPower 默认添加 404、401 界面，防止一直提示 No match found for location with path 'xxx'
   * 2、backEnd.ts(后端控制路由)、frontEnd.ts(前端控制路由) 中也需要加 notFoundAndNoPower 404、401 界面。
   *    防止 404、401 不在 layout 布局中，不设置的话，404、401 界面将全屏显示
   */
  routes: [...staticRoutes, ...notFoundAndNoPower, ...baseRoutes]
})

export const authLogin = async (token?: string) => {
  try {
    if (!token) {
      token = local.get(import.meta.env.VITE_TOKEN_LOCATION_NAME) as string
    }
    if (token) {
      const userStore = useAppsStore()
      const { setToken } = userStore
      await setToken(token)
    } else {
      return false
    }
  } catch (e) {
    console.log('错误', e)
    return false
  }
}

export async function installRouter(app: App) {
  setupRouterGuard(router)
  app.use(router)
  await router.isReady()
}

export default router
